# -*- coding: utf-8 -*-
import win32gui
import win32process
import win32api
import win32con
import time
import pylast
import re
import getpass
from win32com.client import GetObject

from ctypes import *

API_KEY = "ce5d057b7e9b8a70869e100674db263f" 
API_SECRET = "eb6612ac7fe5b303673c5d25db624f92"

class TBBUTTON(Structure):
  _fields_ = [('iBitmap',c_uint)
      ,('idCommand',c_uint)
      ,('fsState',c_byte)
      ,('fsStyle',c_byte)
      ,('bReserved1',c_byte)
      ,('bReserved2',c_byte)
      ,('dwData',c_uint)
      ,('iString',c_uint)
      ]

class TRAYDATA(Structure):
  _fields_ = [('hWnd',c_long)
      ,('uid',c_long)
      ,('uCallBackMessage',c_long)
      ,('Reserved1',c_long*2)
      ,('hIcon',c_long)
      ,('Reserved2',c_int16*6)
      ,('ExePath',c_byte*256)
      ]
def main():
  #pylast 设置参数
  username = raw_input('Your lastfm name:')
  password = getpass.getpass('Your lastfm password:')
  password_hash = pylast.md5(password)
  network = pylast.LastFMNetwork(api_key = API_KEY, api_secret = API_SECRET, username = username, password_hash = password_hash)

  hwnd = win32gui.FindWindow('Shell_TrayWnd',None)
  hwnd = win32gui.FindWindowEx(hwnd,0,'TrayNotifyWnd',None)
  hwnd = win32gui.FindWindowEx(hwnd,0,'SysPager',None)
  hwnd = win32gui.FindWindowEx(hwnd,0,'ToolbarWindow32',None)
  
  kernel32 = windll.LoadLibrary('kernel32.dll')
  psapi = windll.LoadLibrary('psapi.dll')
  GetProcessImageFileNameW = psapi.GetProcessImageFileNameW
  VirtualAllocEx = kernel32.VirtualAllocEx
  OpenProcess = kernel32.OpenProcess
  ReadProcessMemory = kernel32.ReadProcessMemory
  tid, pid = win32process.GetWindowThreadProcessId(hwnd)
  hpro = OpenProcess(win32con.PROCESS_ALL_ACCESS,0,pid)
  baseAddr = VirtualAllocEx(hpro,0,4096,0x1000,0x4)
  bytesRead = c_ulong(0)
  tb = TBBUTTON()
  td = TRAYDATA()
  tip = create_unicode_buffer('\0' * 128)
  cnt = win32gui.SendMessage(hwnd,0x400+24,0,0)

  timedown = 60
  now = ("","")
  last = ("","")
  isCommit = False #当前歌曲是否scroble了
  while(1):
    time.sleep(30) #调整轮询时间，同时能控制多久后开始scroblle
    for i in range(1,cnt):
      win32api.SendMessage(hwnd,0x400+23,i,baseAddr)
      ReadProcessMemory(hpro,baseAddr,byref(tb),sizeof(tb),None)
      ReadProcessMemory(hpro,tb.dwData,byref(td),sizeof(td),None)
      ReadProcessMemory(hpro,tb.iString,tip,128,None) 
      #获取任务栏的系统托盘的图标对应进程
      tid, pid = win32process.GetWindowThreadProcessId(td.hWnd)
      #QeryInformation = 0x400
      tdPro= OpenProcess(0x400,0,pid)
      nSize = 128
      lpFilename = create_unicode_buffer('\0',nSize)
      GetProcessImageFileNameW(tdPro,lpFilename,nSize)
      if re.search('QQMusic',lpFilename.value):
        break
    m = re.match(r"(.+)--(.+)",tip.value)
    if m:
      now = m.group(2,1)
      if now == last:
        if isCommit:
          pass
        else:
          network.scrobble(now[0],now[1],int(time.time()))
          print '%s - %s scroblled' % now
          isCommit = True
      else:
          isCommit = False
      last = now
      
  
if __name__ == '__main__':
  main()
